import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import _ from 'lodash';
import qs from 'qs';
import moment from 'moment';

import { Form } from '@ant-design/compatible';
import { addTab, timeLimit } from '@/utils/utils';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import {
  Card,
  Row,
  Col,
  DatePicker,
  Button,
  Table,
} from 'antd';
import '@ant-design/compatible/assets/index.css';

const { RangePicker } = DatePicker;
const { pathname } = window.location;

interface LogsInfoProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: any;
  location: { query: any };
}

interface LogsInfoState {
  searchValues: any;
}

class LogsInfoElem extends Component<LogsInfoProps, LogsInfoState> {
  columns: any = [
    {
      title: '操作人',
      dataIndex: 'operationName',
      align: 'center',
      width: 100,
    },
    {
      title: '操作时间',
      dataIndex: 'createTime',
      align: 'center',
      width: 160,
    },
    {
      title: '详情',
      dataIndex: 'logs',
      align: 'center',
      width: 200,
      render: (list: any) => (list ? list.map((item: any) => <div key={item}>{item}</div>) : '--'),
    },
  ];

  state: LogsInfoState = {
    searchValues: {
      tariffId: '',
      startTime: '',
      endTime: '',
      pageIndex: 1,
      pageSize: 20,
    },
  };

  static getDerivedStateFromProps(nextProps: any, preState: any) {
    const { location: { query } } = nextProps;
    const { pageIndex, pageSize, ...values } = query;
    return {
      searchValues: {
        ...values,
        pageIndex: Number(pageIndex) || 1,
        pageSize: Number(pageSize) || 20,
      },
    };
  }

  componentDidMount() {
    this.setFieldsValue();
    this.fetchDataValues();
  }

  componentDidUpdate(prevProps: any, prevState: any) {
    const { searchValues } = this.state;
    if (!_.isEqual(searchValues, prevState.searchValues)) {
      this.setFieldsValue();
      this.fetchDataValues();
    }
  }

  setFieldsValue = () => {
    // 设置表单
    const {
      searchValues: {
        pageIndex, pageSize, tariffId, ...values
      },
    } = this.state;
    const params = this.turnValuesType(values);

    const { form: { setFieldsValue } } = this.props;
    setFieldsValue(params);
  };

  turnValuesType = (values: any) => {
    const { startTime, endTime, ...query } = values;
    return {
      // 转换数据类型
      ...query,
      startAndEndDate:
        startTime && endTime
          ? [moment(startTime, 'YYYY-MM-DD'), moment(endTime, 'YYYY-MM-DD')]
          : [],
    };
  };

  fetchDataValues = () => this.fetchAction('fetch', this.getQueryParams());

  getQueryParams = () => {
    const { searchValues } = this.state;
    return searchValues;
  };

  handleSearch = (e: React.FormEvent) => {
    e.preventDefault();
    const { form: { validateFields } } = this.props;
    validateFields((errors, values) => {
      if (errors) return;

      const { startAndEndDate, ...params } = values;
      const startTime = startAndEndDate ? moment(startAndEndDate[0]).format('YYYY-MM-DD') : '';
      const endTime = startAndEndDate ? moment(startAndEndDate[1]).format('YYYY-MM-DD') : '';

      const { location: { query: oldQuery } } = this.props;
      const query = {
        ...oldQuery,
        ...params,
        startTime,
        endTime,
      };

      const { dispatch } = this.props;
      addTab(dispatch, {
        name: '修改日志',
        url: `${pathname}?${qs.stringify(query)}`,
        isTopMenu: true,
      });
    });
  };

  handleReset = () => {
    const { form: { resetFields } } = this.props;
    resetFields();

    const { location: { query: { tariffId } } } = this.props;
    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '修改日志',
      url: `${pathname}?${qs.stringify({ tariffId })}`,
      isTopMenu: true,
    });
  };

  handleChangePage = (pageIndex: number, pageSize: number) => {
    const { searchValues } = this.state;
    const query = { ...searchValues, pageIndex, pageSize };

    const { dispatch } = this.props;
    addTab(dispatch, {
      name: '修改日志',
      url: `${pathname}?${qs.stringify(query)}`,
      isTopMenu: true,
    });
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const type = `cabinetPlansLogsList/${typeName}`;
    const { dispatch } = this.props;
    dispatch({ type, payload });
  };

  render() {
    const {
      searchValues: { pageIndex, pageSize },
    } = this.state;

    const {
      form: { getFieldDecorator },
      dataInfo,
    } = this.props;

    const dataSource = dataInfo ? dataInfo.list : [];
    const pagination: object = {
      total: dataInfo ? dataInfo.count : 0,
      current: pageIndex,
      pageSize,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: () => `共${dataInfo.count || 0}条数据`,
      onChange: this.handleChangePage,
      onShowSizeChange: this.handleChangePage,
    };

    return (
      <Fragment>
        <PageHeader />

        <Card bordered={false} className="searchForm">
          <Form
            hideRequiredMark
            className="tableListForm"
            onSubmit={this.handleSearch}
          >
            <Row gutter={{ md: 8, xl: 24, lg: 48 }}>
              <Col md={8} sm={24}>
                <Form.Item label="起止时间" colon={false}>
                  {getFieldDecorator('startAndEndDate')(
                    <RangePicker disabledDate={timeLimit} placeholder={['开始时间', '结束时间']} />,
                  )}
                </Form.Item>
              </Col>
              <Col md={8} sm={24} />
              <Col md={8} sm={24}>
                <div className="flexFeView">
                  <Button
                    type="primary"
                    htmlType="submit"
                    className="smallButton"
                  >
                    查询
                  </Button>
                  <Button
                    className="addButton smallButton marginL16"
                    type="primary"
                    onClick={this.handleReset}
                  >
                    重置
                  </Button>
                </div>
              </Col>
            </Row>
          </Form>
        </Card>

        <Card bordered={false}>
          <Table
            rowKey="id"
            className="statementTable"
            columns={this.columns}
            dataSource={dataSource}
            pagination={pagination}
          />
        </Card>
      </Fragment>
    );
  }
}

export default connect(({ cabinetPlansLogsList: { dataInfo } }: any) => ({
  dataInfo,
}))(Form.create<LogsInfoProps>()(LogsInfoElem));
